import utils from '@/mixins/utils.js';
import { difference, uniq, flattenDeep } from 'lodash';
export default {
  name: 'area_edit',
  mixins: [utils],
  data() {
    return {
      areaData: {
        areaList: []
      },
      newAreaData: null,
      localIndex: 900000,
      originData: null,
      saveData: {
        addOrUpdateAreaList: [],
        deleteAreaList: [],
        parkUUID: this.$route.query.parkId,
        sessionKey: localStorage.getItem('session_key')
      },
      cur_del_list: []
    };
  },
  created() {
    this.getAreaList();
  },
  methods: {
    updateUpperList(item) {
      this.areaData.areaList.forEach(item => {
        this.cumputeUpperList(item);
      });
    },
    async checkName(rule, value, callback) {
      const list_index = Number(rule.field.split('.')[1]);
      const areaId = this.areaData.areaList[list_index].areaId;
      if (value === '') {
        callback(new Error('请输入区域名称'));
      } else {
        const isVaid = await this.checkIsNameRepeat(value, areaId).catch(err => {
          callback(new Error(err));
        });
        if (!isVaid) {
          callback(new Error(''));
        } else {
          callback();
        }
      }
    },
    checkIsNameRepeat(val, areaId) {
      let params = {
        parkID: this.$route.query.parkId,
        areaName: val
      };
      if (areaId) {
        params.areaId = areaId;
      }
      return new Promise((resolve, reject) => {
        API.fetchGet('/operatorPark/checkAreaNameExist', params).then(
          res => {
            if (res.data) {
              resolve(true);
            } else {
              reject('区域名称已被占用');
            }
          },
          err => {
            reject(err.data.message);
          }
        );
      });
    },
    getAreaList() {
      API.fetchGet('operatorPark/parkArea/getAreaList.do', {
        parkUUID: this.$route.query.parkId
      }).then(
        res => {
          this.originData = JSON.parse(JSON.stringify(res.data));
          this.areaData.areaList = this.formatAreaList(res.data);
          this.setNewAreaData(res.data);
        },
        err => {}
      );
    },
    setNewAreaData(areaList) {
      // 计算新区域的初始对象
      let obj = {
        fakeAreaId: '',
        fakeParentAreaId: '',
        areaId: '',
        areaName: '',
        parentAreaId: '',
        parkArea: false,
        checkedIds: []
      };

      obj.channelList = JSON.parse(JSON.stringify(areaList[0])).channelList.map(item => {
        item.check = false;
        return item;
      });

      this.newAreaData = obj;
    },
    addNewArea() {
      let add_data = JSON.parse(JSON.stringify(this.newAreaData));
      add_data.upperAreaList = this.areaData.areaList
        .filter(item => item.areaName)
        .map(item => {
          return {
            areaName: item.areaName,
            fakeAreaId: item.fakeAreaId
          };
        });
      add_data.fakeAreaId = this.localIndex;
      this.localIndex++;
      this.areaData.areaList.push(add_data);
    },
    formatAreaList(areaList) {
      // 计算上级运营商、计算选择的通道id并设到相应的对象
      areaList.forEach(item => {
        item.checkedIds = item.channelList.filter(item => item.check).map(item => item.channelId);
        item.fakeAreaId = item.areaId;
        item.fakeParentAreaId = item.parentAreaId;
        if (item.parentAreaId !== null) {
          item.upperAreaList = areaList
            .filter(sitem => sitem.areaId !== item.areaId)
            .map(item => {
              return {
                fakeAreaId: item.areaId,
                areaName: item.areaName
              };
            });
        }
      });
      return areaList;
    },
    handleCheckItemChange(val, id, sitem, channel) {
      channel.check = val;
      if (!val || !sitem.fakeParentAreaId) return;

      let parent_item = this.areaData.areaList.find(item => item.fakeAreaId === sitem.fakeParentAreaId);
      const index = this.areaData.areaList.findIndex(item => item.fakeAreaId === sitem.fakeParentAreaId);

      parent_item = JSON.parse(JSON.stringify(parent_item));

      parent_item.checkedIds = parent_item.checkedIds.filter(item => item !== id);
      parent_item.channelList.some(item => {
        if (item.channelId === id) {
          item.check = false;
          return true;
        }
      });
      this.areaData.areaList.splice(index, 1, parent_item);
    },
    cumputeUpperList(cur_item) {
      cur_item.upperAreaList = this.areaData.areaList
        .filter(item => item.areaName && item.fakeAreaId !== cur_item.fakeAreaId)
        .map(item => {
          return {
            areaName: item.areaName,
            fakeAreaId: item.fakeAreaId
          };
        });
    },

    delAreaItem(item, index) {
      this.$confirm(
        '<p>确定删除“内场区域”？</p><p>删除后：</p><p>1、如果当前区域存在子区域会一并删除；</p><p>2、属于内场区域的进出场纪录将无法查看。</p>',
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          customClass: 'mgr-msg-box',
          confirmButtonClass: 'el-button el-button--danger',
          dangerouslyUseHTMLString: true
        }
      ).then(() => {
        this.getChildArea(item.fakeAreaId);
        this.areaData.areaList = difference(this.areaData.areaList, this.cur_del_list);
        if (this.areaData.areaList.length === 1) {
          let temp = this.areaData.areaList[0];
          temp.checkedIds = temp.channelList.map(item => {
            item.check = true;
            return item.channelId;
          });
          this.areaData.areaList.splice(0, 1, temp);
        }
      });
    },
    getChildArea(id) {
      const cur_item = this.areaData.areaList.find(item => item.fakeAreaId === id);
      this.cur_del_list.push(cur_item);
      const temp = this.areaData.areaList.filter(item => item.parentAreaId === id || item.fakeParentAreaId === id);
      if (temp.length) {
        temp.forEach(item => {
          this.getChildArea(item.fakeAreaId);
        });
      }
    },
    testForm() {
      return new Promise(resolve => {
        this.$refs['areaData'].validate(valid => {
          if (valid) {
            resolve(true);
          } else {
            resolve(false);
          }
        });
      });
    },
    testChannelIsChecked() {
      // 如果没有子区域
      if (this.areaData.areaList.length === 1) {
        return {
          isAllChecked: true
        };
      }

      const all_ids = this.originData[0].channelList.map(item => item.channelId);
      const checked_ids = flattenDeep(this.areaData.areaList.map(item => item.checkedIds));
      const diff_result = difference(all_ids, uniq(checked_ids));

      // 如果所有通道都选择了
      if (!diff_result.length) {
        return {
          isAllChecked: true
        };
      }

      // 有通道未被选择
      return {
        isAllChecked: false,
        channel_unchecked_list: this.originData[0].channelList
          .filter(item => diff_result.includes(item.channelId))
          .map(item => item.entranceName)
          .join(' , ')
      };
    },
    async submiteForm() {
      const test_result = await this.testForm();
      if (!test_result) return;
      const isAllChecked_result = this.testChannelIsChecked();
      if (!isAllChecked_result.isAllChecked) {
        this.showToast(
          `通道：${isAllChecked_result.channel_unchecked_list} 未被任何区域绑定，请绑定区域后提交`,
          2,
          3500
        );
        return;
      }
      this.computedSubmiteFormData();
      API.fetchPost('operatorPark/parkArea/saveParkAreaList.do', this.saveData).then(
        res => {
          this.showToast('区域修改成功', 1, 1500);
          setTimeout(() => {
            this.$router.push({
              name: 'allParkinglotInfo',
              query: this.$route.query
            });
          }, 1500);
        },
        err => {}
      );
    },
    computedSubmiteFormData() {
      this.saveData.deleteAreaList = this.cur_del_list.filter(item => !!item.areaId).map(item => item.areaId);

      this.saveData.addOrUpdateAreaList = JSON.parse(JSON.stringify(this.areaData.areaList)).map(item => {
        delete item.upperAreaList;
        delete item.checkedIds;
        return item;
      });
    },
    back() {
      this.$router.push({
        name: 'allParkinglotInfo',
        query: this.$route.query
      });
    },
    linkToTips() {
      this.$router.push({
        name: 'areaTips',
        query: this.$route.query
      });
    }
  }
};
